#include "quirrel_base.hpp"
#include <cstdarg>

#include "vm_type_register.hpp"
#include "fmt/printf.h"

VMHelper::VMHelper () : vm {sq_open (1024)}
{
    sq_setcompilererrorhandler (vm, &compile_error_handler);
    sq_enabledebuginfo (vm, true);
    sq_notifyallexceptions (vm, true);
    sq_setprintfunc (vm, &printfunc, &errorfunc);
    RegisterEditorType (vm);
}

VMHelper::~VMHelper ()
{
    sq_close (vm);
}

void VMHelper::compile_error_handler(HSQUIRRELVM, const SQChar* desc, const SQChar* source, SQInteger line, SQInteger column)
{
    fmt::fprintf(stderr, "Compile Error At Source %s:%d:%d, Description: %s\n", source, line, column, desc);
}

void VMHelper::printfunc(HSQUIRRELVM v, const SQChar* s, ...)
{
    va_list vl;
    va_start(vl, s);
    vfprintf(stdout, s, vl);
    va_end(vl);
}

void VMHelper::errorfunc(HSQUIRRELVM v, const SQChar* s, ...)
{
    va_list vl;
    va_start(vl, s);
    vfprintf(stderr, s, vl);
    va_end(vl);
}

VMHelper& VMHelper::GetVMInstance()
{
    static VMHelper instance;
    return instance;
}
